<?php

/**
*  ajax front to download resume 
*  pipapai.com
*/
require_once(OC::$SERVERROOT."/apps/resumes/lib/helper.php");
require_once(OC::$SERVERROOT."/apps/resumes/lib/download.php");

// Check if we are a user
$companyid = 0;
if(!OC_User::isLoggedIn()) {
   $app = PFactory::getApplication();
   $companyid = $app->getUserState('resumeshare_companyid', 0);
   if(!$companyid) {
      echo PUtil::checkUserLogin(true);
      exit;
   }
}
else {
   $companyid = PFactory::getMasterUser()->id;
}

// use 0 as expiration to avoid date out-of-sync 
setcookie('DOWNLOAD_DONE', '1', 0, '/');

$datadir = getUserDataDir($companyid); 
$extdir = getUserExtDir($companyid); 

$resumes = PResumeController::getResumeAsFiles($companyid);
if(empty($resumes)) {
   $tmpl = new OC_Template('', '404', 'base');
   $tmpl->assign('error', '简历未找到');
   $tmpl->printPage();
   return; 
}

// reinit filesystem so subaccount can point to correct path 
// we need to tear down for automatic mapping because it put subaccount in wrong mounting point 
\OC\Files\Filesystem::tearDown();
\OC\Files\Filesystem::initMountPoints(PFactory::getMasterUser()->get('id'));

if(count($resumes) <= 1) {
   $resume = $resumes[0]; 

   // resumefile is array in format:  aa/bb/cc/<hash key>/<version>/source/resume.html  
   $resume->resumefile = PStorage::getResumeFilePath($companyid, $resume, $resume->source);

   // resume->resumefile must be valid for jobseeker's source 
   if(empty($resume->resumefile)) {
      $tmpl = new OC_Template('', '404', 'base');
      $tmpl->assign('error', '简历未找到');
      $tmpl->printPage();
      return; 
   }

   $humanpath = $resume->name . "-" . $resume->jobtitle; 

   // savedir will be like: /data/<datadisk>/company/233/456/789/1789456233/resumes/download/<resume-name>
   $savedir = OC::$SERVERROOT."/data".$datadir."/company/" . $extdir . "/resumes/download/" . $resume->name; 
   if(is_dir($savedir)) {
      $savedir = createUniqueDir(dirname($savedir), $resume->name);
   }
   else {
      JFolder::create($savedir);
   }

   $pdfdir = $savedir . "/" . $humanpath;
   JFolder::create($pdfdir);

   if(!is_dir($savedir) || !is_dir($pdfdir)) {
      JFolder::delete($savedir);
      $tmpl = new OC_Template('', '404', 'base');
      $tmpl->assign('error', '权限不够');
      $tmpl->printPage();
      return; 
   }

   $sourcefolders = PResumesDownloader::copyFiles($resume, null, $savedir); 
   // generating PDFs
   $pdffiles = array();
   foreach($sourcefolders as $source) {
      $pdf = PResumesDownloader::generatePDF("/data".$datadir."/company/".$extdir."/resumes/download/".basename($savedir), $source, $pdfdir);
      if($pdf !== false)
         array_push($pdffiles, $pdf);
   }

   if(PResumesDownloader::mergePDF($pdffiles, $savedir."/".$resume->name.".pdf")) {
      $file = $savedir."/".$resume->name.".pdf";
      $filename = basename($file);

      // we cannot use owncloud method it will not handle download file name correctly 
      // $storage->chroot($parentdir."/download/".basename($savedir));
      // OC_Files::get("/", array($filename), $_SERVER['REQUEST_METHOD'] == 'HEAD' ? true : false);

      header('Content-Type: application/pdf');
     
      jimport('joomla.environment.browser');
      $browser = JBrowser::getInstance();
      $userBrowser = $browser->getBrowser();
      $userAgent = $browser->getAgentString(); 
      if ($userBrowser == 'msie' || strpos($userAgent, "Trident/") !== false) {
         header('Content-Disposition: attachment; filename="'.rawurlencode($filename).'"');
      } else {
         header('Content-Disposition: attachment; filename*=UTF-8\'\''.$filename.'; filename="'.$filename.'"');
      }
      header('Content-Transfer-Encoding: binary');
      header('Content-Length: ' . filesize($file));
      @readfile($file);
      JFolder::delete($savedir);
      return;
   }

   // just do a zip download 
   $storage = \OC\Files\Filesystem::getView();
   $storage->chroot($companyid."/resumes/download/".basename($savedir));
   OC_Files::get("", array(basename($pdfdir)), $_SERVER['REQUEST_METHOD'] == 'HEAD' ? true : false);

   JFolder::delete($savedir);
}
else if(count($resumes) <= 10) {

   $savedir = OC::$SERVERROOT."/data".$datadir."/company/" . $extdir . "/resumes/download/download"; 
   if(is_dir($savedir))
      $savedir = createUniqueDir(dirname($savedir), "download");
   else 
      JFolder::create($savedir); 

   $pdfdir = $savedir . "/download";
   JFolder::create($pdfdir);

   if(!is_dir($pdfdir)) {
      JFolder::delete($savedir);
      $tmpl = new OC_Template('', '404', 'base');
      $tmpl->assign('error', '权限不够');
      $tmpl->printPage();
      return; 
   }
 

   foreach($resumes as $resume) {

      // resumefile is array in format:  aa/bb/cc/<hash key>/<version>/source/resume.html  
      $resume->resumefile = PStorage::getResumeFilePath($companyid, $resume, $resume->source);
      
      // resume->resumefile must be valid for jobseeker's source 
      if(empty($resume->resumefile)) {
         continue; 
      }

      $humanpath = $resume->name . "-" . str_replace('/', '|', $resume->jobtitle); 

      JFolder::create($savedir."/".$humanpath);

      $sourcefolders = PResumesDownloader::copyFiles($resume, null, $savedir."/".$humanpath);

      // generating PDFs
      foreach($sourcefolders as $source) {
         PResumesDownloader::generatePDF("/data".$datadir."/company/".$extdir."/resumes/download/".basename($savedir)."/".$humanpath, $source, $pdfdir);
      }

   }

   $storage = \OC\Files\Filesystem::getView();
   $storage->chroot($companyid."/resumes/download/".basename($savedir));

   OC_Files::get("", array("download"), $_SERVER['REQUEST_METHOD'] == 'HEAD' ? true : false);
   JFolder::delete($savedir);
}
else {
   setcookie('DOWNLOAD_DELAYED', '1', 0, '/');
   // add to delay task 
   $status = DelayTaskJob::add(
            array('summary'=>count($resumes).'份简历下载', 
                  'userid'=>PFactory::getMasterUser()->get('id'), 
                  'owner'=>OC_User::getUser(), 
                  'handler'=>'/usr/bin/php ' . realpath(JPATH_SITE . '/../cloud/cli/resumedownload.php'), 
                  'parameters'=>json_encode(JArrayHelper::getColumn($resumes, 'id')), 
                  'exclusive'=> false,  // support multiple download concurrently 
                  'duplicate'=> false   // don't support duplicate task per-user 
                 )
            );

   if($status === false) {
      setcookie('DOWNLOAD_DELAYED_ERROR', '1', 0, '/');
   }
   else if($status === 'duplicate-job') {
      setcookie('DOWNLOAD_DELAYED_DUPLICATE', '1', 0, '/');
   }

   // send 204 header for no-response request 
   header("status: 204"); 
   exit();
}


